import { FC, useEffect, useState } from 'react'
import axios from '@/http'
import { TChat } from '@type'
import { message, Modal, Space, Table } from 'antd'
import { formatTime } from '@/util'
import { ColumnsType } from 'antd/lib/table'
import { ExclamationCircleOutlined } from '@ant-design/icons'

const Chat: FC<{ username?: string }> = ({ username }) => {
  const { confirm } = Modal

  const [chatList, setChatList] = useState<TChat[]>([])
  const [loading, setloading] = useState(false)
  const columns: ColumnsType<TChat> = [
    {
      title: 'id',
      dataIndex: 'id'
    },
    {
      title: '消息',
      dataIndex: 'message'
    },
    {
      title: '发送时间',
      dataIndex: 'time',
      render: (_, { time }) => {
        return <>{formatTime(time)}</>
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, data) => {
        const { id } = data
        return (
          <Space size="middle">
            <a onClick={() => showDeleteConfirm(id)} style={{ color: 'red' }}>
              删除
            </a>
          </Space>
        )
      }
    }
  ]
  const showDeleteConfirm = (id: number) => {
    confirm({
      title: '删除消息?',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除此消息？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        startDel(id)
      }
    })
  }
  const startDel = (id: number) => {
    axios
      .post('/chat/del', {
        id
      })
      .then(res => {
        res.data.error === -1 ? message.success('删除成功') : message.error('删除失败')
        getUserChatContent()
      })
  }
  const getUserChatContent = () => {
    setloading(true)
    axios
      .get('/chat/search', {
        params: {
          username,
          Tousername: '2628735401'
        }
      })
      .then(res => {
        console.log(res)
        res.data.error === -1 && setChatList(res.data.data)
      })
      .finally(() => {
        setloading(false)
      })
  }
  useEffect(() => {
    getUserChatContent()
  }, [])

  return (
    <>
      <div>
        <Table
          scroll={{ y: 250 }}
          rowKey={record => record.id}
          loading={loading}
          columns={columns}
          pagination={false}
          dataSource={chatList}
        />
      </div>
    </>
  )
}
export default Chat
